package cn.edu.zafu.bigdata.fui.TCPnUTP;

import java.net.*;
import java.text.SimpleDateFormat;
import java.util.Date;

public class UDPServer {
    public static void main(String[] args) {
        int port = 1234; // 服务器端口号
        try (DatagramSocket serverSocket = new DatagramSocket(port)) {
            System.out.println("UDP Server is running and waiting for client request...");

            byte[] receiveBuffer = new byte[1024];
            byte[] sendBuffer;

            while (true) {
                DatagramPacket receivePacket = new DatagramPacket(receiveBuffer, receiveBuffer.length);
                serverSocket.receive(receivePacket);
                String sentence = new String(receivePacket.getData(), 0, receivePacket.getLength()).trim();
                System.out.println("Client says: " + sentence);

                // 获取当前时间
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String currentTime = sdf.format(new Date());

                // 发送时间给客户端
                sendBuffer = currentTime.getBytes();
                DatagramPacket sendPacket = new DatagramPacket(sendBuffer, sendBuffer.length, receivePacket.getAddress(), receivePacket.getPort());
                serverSocket.send(sendPacket);
                System.out.println("Time sent: " + currentTime);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}